package com.siashan.toolkit.sms.yunpian;

import com.siashan.toolkit.sms.cache.SmsCacheAutoConfiguration;
import com.siashan.toolkit.sms.cache.SmsCacheTemplate;
import com.siashan.toolkit.sms.core.entity.SmsFrequencyLimitConfig;
import com.siashan.toolkit.sms.core.entity.SmsTemplate;
import com.siashan.toolkit.sms.core.entity.SmsWhiteList;
import com.siashan.toolkit.sms.core.utils.SmsTemplateUtils;
import com.siashan.toolkit.sms.yunpian.core.YunpianSmsConfig;
import com.siashan.toolkit.sms.yunpian.core.YunpianSmsSendExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.List;
import java.util.Map;

/**
 * 云片发送端点自动配置
 *
 * @author siashan
 * @since v1.0.1
 */
@Configuration
@EnableConfigurationProperties(YunpianSmsProperties.class)
@Import(SmsCacheAutoConfiguration.class)
public class YunpianSmsAutoConfiguration {


    @Autowired
    private YunpianSmsProperties yunpianSmsProperties;

    @Autowired
    private SmsCacheTemplate smsCacheTemplate;

    /**
     * 构造云片发送处理
     *
     * @return 云片发送处理
     */
    @Bean
    @ConditionalOnMissingBean
    public YunpianSmsSendExecutor yunpianSmsSendExecutor() {
        List<SmsTemplate> templateList = yunpianSmsProperties.getTmpls();
        Map<String, SmsTemplate> templateMap = SmsTemplateUtils.transMap(templateList);
        YunpianSmsConfig config = yunpianSmsProperties.getConfig();
        SmsWhiteList whiteList = yunpianSmsProperties.getWhiteList();
        SmsFrequencyLimitConfig frequencyLimit = yunpianSmsProperties.getFrequencyLimit();
        YunpianSmsSendExecutor executor = new YunpianSmsSendExecutor(config,templateMap, whiteList,frequencyLimit);
        return executor;
    }

    /**
     * 构造百度云发送模板类
     *
     * @return 百度云发送模板类
     */
    @Bean
    @ConditionalOnMissingBean
    public YunpianSmsTemplate yunpianSmsTemplate() {
        YunpianSmsTemplate yunpianSmsTemplate = new YunpianSmsTemplate(smsCacheTemplate, yunpianSmsSendExecutor());
        return yunpianSmsTemplate;
    }

}
